package com.changzhi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.changzhi.common.constans.RedisConstans;
import com.changzhi.common.enums.DressUpTypeEnum;
import com.changzhi.common.exception.ServiceException;
import com.changzhi.ldyl.model.*;
import com.changzhi.ldyl.model.dto.PrizeDto;
import com.changzhi.mapper.*;
import com.changzhi.service.GiftService;
import com.changzhi.service.UserDressUpService;
import com.changzhi.service.UserService;
import com.changzhi.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:
 * @author: 小落
 * @date: 2020年12月15日
 */
@Slf4j
@Service
public class GiftServiceImpl implements GiftService {

	@Resource
	private ActivityRecordMapper activityRecordMapper;
	@Resource
	private UserDressUpMapper userDressUpMapper;
	@Resource
	private SysDictMapper sysDictMapper;
	@Resource
	private GiftConfigMapper giftConfigMapper;
	@Resource
	private UserGiftBackpackMapper userGiftBackpackMapper;
	@Resource
	private DressUpConfigMapper dressUpConfigMapper;
	@Resource
	private DressUpGiveConfigMapper dressUpGiveConfigMapper;
	@Autowired
	private UserService userService;
	@Autowired
	private RedisUtil redisUtil;
	@Resource
	private FamilyMapper familyMapper;
	@Autowired
	private UserDressUpService userDressUpService;
	@Resource
	private ActivityAwardMapper activityAwardMapper;

	//保存新装扮物品（挂件、气泡、尾灯、主页装饰动画）
	@Override
	public DressUpConfig saveUserDress(PrizeDto prizeDto) {
		String userId = prizeDto.getUserId();
		String remark = prizeDto.getRemark();
		ActivityPrize prize = prizeDto.getPrize();
		Integer dressUpId = prize.getGiftId();
		Integer activityId = prize.getActivityId();
		Integer multiple = prize.getNum();
		Integer prizeType = prize.getType();
		if (userId == null) {
			throw new ServiceException("用户Id不能为空");
		}
		if (dressUpId == null) {
			throw new ServiceException("装扮名称不能为空");
		}
		DressUpConfig dressUpConfig = dressUpConfigMapper.selectById(dressUpId);
		if (dressUpConfig == null) {
			throw new ServiceException("装扮不存在");
		}
		Integer type = dressUpConfig.getType();
		User user = userService.getUser(userId);
		if (user == null) {
			throw new ServiceException("用户不存在");
		}
		LocalDateTime now = LocalDateTime.now();
		//判断是否是否存在
		boolean existDressUp = userDressUpMapper.isExistDressUp(user.getUserId(), dressUpId);
		if(existDressUp){
			//增加天数
			addDressUpTime(activityId, user.getUserId(), dressUpId, dressUpConfig, multiple, prizeType);
			//插入领取记录表
			ActivityRecord record = new ActivityRecord();
			record.setActivityId(activityId);
			record.setUserId(userId);
			record.setGiftId(dressUpId);
			record.setValue(0);
			record.setContent(dressUpConfig.getName() + "（"+ dressUpConfig.getDuration() +"天）");
			record.setType(prizeType);
			activityRecordMapper.insert(record);
			//插入奖励记录表
			ActivityAward award = new ActivityAward();
			award.setActivityId(activityId);
			award.setType(prizeType);
			award.setUserId(userId);
			award.setGiftId(dressUpId);
			award.setSource(prize.getSource());
			award.setIcon(prize.getIcon());
			award.setNum(prize.getNum());
			award.setName(dressUpConfig.getName());
			award.setUseNum(prize.getUseNum());
			award.setRoundId(prize.getRoundId());
			award.setTotalValue(prize.getTotalValue());
			activityAwardMapper.insert(award);
			return null;
		}
		//2.按照父子级排序，查询出每种类型中排序最高的挂件
		List<UserDressUp> upList;
		if(DressUpTypeEnum.USER_LABEL.getValue().equals(type)){
			upList = userDressUpMapper.selectLabelMaxList(user.getUserId(), dressUpId, type);
		} else {
			upList = userDressUpMapper.selectDressUpMaxList(user.getUserId(), dressUpId, type);
		}
		if(CollectionUtils.isEmpty(upList)){
			return null;
		}
		//新增数据组装
		UserDressUp newDressUp = upList.stream().filter(t -> t.getId() == null).collect(Collectors.toList()).get(0);
		UserDressUp userDressUp = new UserDressUp();
		userDressUp.setUserId(user.getUserId());
		userDressUp.setType(dressUpConfig.getType());
		userDressUp.setDressId(dressUpId);
		userDressUp.setPrice(0);
		Integer duration = newDressUp.getDuration();
		userDressUp.setDuration(duration == null ? 0 : duration * multiple);
		userDressUp.setCreateTime(now);
		userDressUp.setUpdateTime(now);
		userDressUp.setStatus(1);
		userDressUp.setLimitedType(2);
		userDressUp.setRemark(remark);
		//3.判断第一个挂件是单一还是并列
		UserDressUp firstDressUp = upList.get(0);
		if(firstDressUp.getShowType() == 0){
			//4.单一挂件，判断挂件是否为当前挂件，是则变更为穿戴，其他挂件变更为不穿戴
			//用户已存在气泡框则不佩戴
			if(DressUpTypeEnum.BUBBLE.getValue().equals(type) || DressUpTypeEnum.HOME_DECORATION.getValue().equals(type)){
				boolean exist = userDressUpMapper.isExistDressUp2(user.getUserId(), type);
				if(exist){
					userDressUp.setStatus(0);
				}
			} else if(DressUpTypeEnum.USER_LABEL.getValue().equals(type)){

			} else {
				//其他挂件变更为不穿戴
				LambdaUpdateWrapper<UserDressUp> wrapper = new LambdaUpdateWrapper<>();
				wrapper.set(UserDressUp::getStatus, 0);
				wrapper.eq(UserDressUp::getUserId, user.getUserId()).eq(UserDressUp::getType, type);
				userDressUpService.update(wrapper);
				if(!dressUpId.equals(firstDressUp.getDressId())){
					//第一个变为佩戴
					UserDressUp wearDressUp = new UserDressUp();
					wearDressUp.setId(firstDressUp.getId());
					wearDressUp.setStatus(1);
					userDressUpService.updateById(wearDressUp);
					//当前变为不佩戴
					userDressUp.setStatus(0);
				}
			}
		} else {//并列
			//5.并列挂件，过滤出所有并列挂件，变更为穿戴，其他挂件变更为不穿戴
			Map<Integer,List<UserDressUp>> groupList = upList.stream().collect(Collectors.groupingBy(UserDressUp::getShowType));
			//并列的装饰数据
			List<UserDressUp> multiDressUpList = groupList.get(1);
			//找出父级相同的新增挂件和拥有的挂件对比，是否需要佩戴
			List<UserDressUp> compareDressUpList = multiDressUpList.stream().filter(t -> t.getParentId().equals(newDressUp.getParentId())).collect(Collectors.toList());
			if(compareDressUpList.size() > 1){
				for (UserDressUp up : compareDressUpList) {
					if(up.getDressId().equals(newDressUp.getDressId())){
						continue;
					}
					if(up.getParentWeight() > newDressUp.getParentWeight()){
						userDressUp.setStatus(0);
						break;
					} else if(up.getParentWeight().equals(newDressUp.getParentWeight())){
						if(up.getWeight() > newDressUp.getWeight()){
							userDressUp.setStatus(0);
							break;
						}
					}
				}
			}
			if(newDressUp.getShowType() == 0){
				userDressUp.setStatus(0);
			}
			//
			List<Long> idList = multiDressUpList.stream().filter(t -> t.getId() != null).map(p -> p.getId()).collect(Collectors.toList());
			//如果当前添加的挂件为佩戴状态并且已有相同类型的挂件，则相同类型的挂件应该变为不佩戴
			if(userDressUp.getStatus() == 1 && compareDressUpList.size() > 1){
				//过滤
				List<Long> filterIdList = compareDressUpList.stream().filter(t -> t.getId() != null).map(p -> p.getId()).collect(Collectors.toList());
				idList = idList.stream().filter(t-> !filterIdList.contains(t)).collect(Collectors.toList());
			}
			//其他挂件变更为不穿戴
			LambdaUpdateWrapper<UserDressUp> wrapper = new LambdaUpdateWrapper<>();
			wrapper.set(UserDressUp::getStatus, 0);
			wrapper.eq(UserDressUp::getUserId, user.getUserId()).eq(UserDressUp::getType, type);
			if(!CollectionUtils.isEmpty(idList)){
				//并列最高的佩戴
				LambdaUpdateWrapper<UserDressUp> wrapper1 = new LambdaUpdateWrapper<>();
				wrapper1.set(UserDressUp::getStatus, 1);
				wrapper1.in(UserDressUp::getId, idList);
				userDressUpService.update(wrapper1);
				wrapper.notIn(UserDressUp::getId, idList);
			}
			userDressUpService.update(wrapper);
		}
		//是否设置过期时间
		if(dressUpConfig.getDuration() != null && dressUpConfig.getDuration() != 0){
			if((DressUpTypeEnum.BUBBLE.getValue().equals(userDressUp.getType()) && userDressUp.getStatus() == 1) || !DressUpTypeEnum.BUBBLE.getValue().equals(userDressUp.getType())){
				userDressUp.setEffectiveTime(now);
				userDressUp.setExpireTime(now.plusDays(userDressUp.getDuration()));
			}
		}
		userDressUpService.save(userDressUp);
		//插入记录表
		DressUpGiveConfig upGiveConfig = new DressUpGiveConfig();
		upGiveConfig.setConfigType(1);
		upGiveConfig.setDressupType(userDressUp.getType());
		upGiveConfig.setDressupTypeId(newDressUp.getParentId());
		upGiveConfig.setDressupId(userDressUp.getDressId());
		upGiveConfig.setAccountId(user == null ? null : user.getAccountId());
		upGiveConfig.setUserId(user.getUserId());
		upGiveConfig.setEffectiveTime(userDressUp.getEffectiveTime());
		upGiveConfig.setExpireTime(userDressUp.getExpireTime());
		upGiveConfig.setUserDressupId(userDressUp.getId());
		upGiveConfig.setSource(2);
		userDressUp.setRemark(remark);
		upGiveConfig.setHandlerUserid("0");
		dressUpGiveConfigMapper.insert(upGiveConfig);
		//删除缓存
		removeCache(user.getUserId(), type);
		//插入领取记录表
		ActivityRecord record = new ActivityRecord();
		record.setActivityId(activityId);
		record.setUserId(userId);
		record.setGiftId(dressUpId);
		record.setValue(0);
		record.setContent(dressUpConfig.getName() + "（"+ dressUpConfig.getDuration() +"天）");
		record.setType(prizeType);
		activityRecordMapper.insert(record);
		//插入奖励记录表
		ActivityAward award = new ActivityAward();
		award.setActivityId(activityId);
		award.setType(prizeType);
		award.setUserId(userId);
		award.setGiftId(dressUpId);
		award.setSource(prize.getSource());
		award.setIcon(prize.getIcon());
		award.setNum(prize.getNum());
		award.setName(dressUpConfig.getName());
		award.setUseNum(prize.getUseNum());
		award.setRoundId(prize.getRoundId());
		award.setTotalValue(prize.getTotalValue());
		activityAwardMapper.insert(award);
		//返回
		return dressUpConfig;
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public GiftConfig savePrize(PrizeDto prizeDto){
		String userId = prizeDto.getUserId();
		ActivityPrize prize = prizeDto.getPrize();
		Integer giftId = prize.getGiftId();
		Integer activityId = prize.getActivityId();
		Integer num = prize.getNum();
		Integer type = prize.getType();
		// 获取奖品信息
		GiftConfig giftConfig = giftConfigMapper.selectById(giftId);
		if (giftConfig == null) {
			log.error("methodName:receiveGift,giftId={},error=giftConfig不存在", giftId);
			return null;
		}
		for (int i = 0; i < num; i++) {
			UserGiftBackpack backpack = new UserGiftBackpack();
			backpack.setUserId(userId);
			backpack.setGiftId(giftId);
			backpack.setName(giftConfig.getName());
			backpack.setValue(giftConfig.getValue());
			backpack.setIconUrl(giftConfig.getIconUrl());
			backpack.setEffects(giftConfig.getEffects());
			backpack.setLovenum(giftConfig.getLovenum());
			backpack.setStatus(0);
			backpack.setSource(3);
			backpack.setGiftType(giftConfig.getGiftType());
			userGiftBackpackMapper.insert(backpack);
		}
		//插入领取记录表
		if(type != null){
			ActivityRecord record = new ActivityRecord();
			record.setActivityId(activityId);
			record.setUserId(userId);
			record.setGiftId(giftId);
			record.setNum(num);
			record.setValue(giftConfig.getValue() * num);
			record.setContent(giftConfig.getName());
			record.setType(type);
			if(giftConfig.getGiftType() == 1){
				//装扮物品
				LambdaQueryWrapper<SysDict> wrapper = new LambdaQueryWrapper<>();
				wrapper.eq(SysDict::getCode,"DRESS_UP").eq(SysDict::getId, giftConfig.getDressId());
				SysDict sysDict = sysDictMapper.selectOne(wrapper);
				if(sysDict != null && StringUtils.isNotBlank(sysDict.getProperty4())){
					record.setContent(record.getContent() + "（"+ sysDict.getProperty4() +"天）");
					giftConfig.setName(record.getContent());
				}
			}
			activityRecordMapper.insert(record);
			//插入奖励记录表
			ActivityAward award = new ActivityAward();
			award.setActivityId(activityId);
			award.setType(type);
			award.setUserId(userId);
			award.setGiftId(giftId);
			award.setSource(prize.getSource());
			award.setIcon(prize.getIcon());
			award.setNum(prize.getNum());
			award.setName(giftConfig.getName());
			award.setUseNum(prize.getUseNum());
			award.setRoundId(prize.getRoundId());
			award.setTotalValue(prize.getTotalValue());
			activityAwardMapper.insert(award);
		}
		return giftConfig;
	}

	/**
	 * 添加家族标签
	 * @param prizeDto
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveFamilyLabel(PrizeDto prizeDto){
		String familyId = prizeDto.getUserId();
		ActivityPrize prize = prizeDto.getPrize();
		Integer dressConfigId = prize.getGiftId();
		Integer activityId = prize.getActivityId();
		Integer type = prize.getType();
		String remark = prizeDto.getRemark();

		Family family = familyMapper.selectById(familyId);
		if (family == null) {
			log.error("methodName:saveFamilyLabel，familyId={}", familyId);
			return;
		}
		// 设置有效期
		DressUpGiveConfig record = new DressUpGiveConfig();
		record.setRemark(remark);
		DressUpConfig config = dressUpConfigMapper.selectById(dressConfigId);
		if (config == null) {
			log.error("methodName:saveFamilyLabel，配置不存在，familyId={}, dressConfigId={}", familyId, dressConfigId);
			return;
		}
		//判断是否存在家族标签
		LambdaQueryWrapper<DressUpGiveConfig> upGiveConfigWrapper = new LambdaQueryWrapper<>();
		upGiveConfigWrapper.eq(DressUpGiveConfig::getAccountId,family.getAccountId()).eq(DressUpGiveConfig::getConfigType, 3)
				.eq(DressUpGiveConfig::getDressupType, DressUpTypeEnum.USER_LABEL.getValue()).eq(DressUpGiveConfig::getDressupId, dressConfigId).last("limit 1");
		DressUpGiveConfig upGiveConfig = dressUpGiveConfigMapper.selectOne(upGiveConfigWrapper);
		if (upGiveConfig == null) {// 新增保存
			if (config.getDuration() != null && config.getDuration() != 0) {
				LocalDateTime now = LocalDateTime.now();
				record.setEffectiveTime(now);
				record.setExpireTime(now.plusDays(config.getDuration()));
			} else {
				record.setEffectiveTime(null);
				record.setExpireTime(null);
			}
			record.setConfigType(3);// 家族主页
			record.setDressupType(DressUpTypeEnum.FAMILY_LABEL.getValue());
			record.setDressupTypeId(config.getSubType());
			record.setDressupId(config.getId().intValue());
			record.setAccountId(family.getAccountId());
			record.setFamilyId(family.getId());
			record.setHandlerUserid("0");
			record.setCreateTime(LocalDateTime.now());
			dressUpGiveConfigMapper.insert(record);
		} else {// 更新
			record.setId(upGiveConfig.getId());
			record.setUpdateTime(LocalDateTime.now());
			if (config.getDuration() != null && config.getDuration() != 0) {
				record.setExpireTime(upGiveConfig.getExpireTime().plusDays(config.getDuration()));
			} else {
				record.setEffectiveTime(null);
				record.setExpireTime(null);
			}
			dressUpGiveConfigMapper.updateById(record);
		}
		//插入领取记录表
		ActivityRecord activityRecord = new ActivityRecord();
		activityRecord.setActivityId(activityId);
		activityRecord.setUserId(family.getId());
		activityRecord.setGiftId(dressConfigId);
		activityRecord.setValue(0);
		activityRecord.setContent(config.getName() + "（"+ config.getDuration() +"天）");
		activityRecord.setType(type);
		activityRecordMapper.insert(activityRecord);
		//插入奖励记录表
		ActivityAward award = new ActivityAward();
		award.setActivityId(activityId);
		award.setType(type);
		award.setUserId(familyId);
		award.setGiftId(config.getId().intValue());
		award.setSource(prize.getSource());
		award.setIcon(prize.getIcon());
		award.setNum(prize.getNum());
		award.setName(config.getName());
		award.setUseNum(prize.getUseNum());
		award.setRoundId(prize.getRoundId());
		award.setTotalValue(prize.getTotalValue());
		activityAwardMapper.insert(award);
	}


	//保存新装扮物品（挂件、气泡、尾灯、主页装饰动画）
	@Deprecated
	@Override
	public DressUpConfig saveUserDress(Integer activityId, String userId, Integer dressUpId, Integer type) {
		ActivityPrize prize = new ActivityPrize();
		prize.setActivityId(activityId);
		prize.setGiftId(dressUpId);
		prize.setType(type);
		prize.setNum(1);
		return saveUserDress(new PrizeDto(userId, prize, ""));
	}

	//保存新装扮物品（挂件、气泡、尾灯、主页装饰动画）
	@Deprecated
	@Override
	public DressUpConfig saveUserDress(Integer activityId, String userId, Integer dressUpId, Integer prizeType, Integer multiple, String remark) {
		ActivityPrize prize = new ActivityPrize();
		prize.setActivityId(activityId);
		prize.setGiftId(dressUpId);
		prize.setType(prizeType);
		prize.setNum(multiple);
		return saveUserDress(new PrizeDto(userId, prize, ""));
	}

	private void addDressUpTime(Integer activityId, String userId, Integer dressUpId, DressUpConfig dressUpConfig, Integer multiple, Integer prizeType){
		Integer duration = dressUpConfig.getDuration() * multiple;
		//增加时长
		userDressUpMapper.updateDressUpTime(userId, dressUpId, duration);
		//删除缓存
		removeCache(userId, dressUpConfig.getType());
		//插入领取记录表
		ActivityRecord record = new ActivityRecord();
		record.setActivityId(activityId);
		record.setUserId(userId);
		record.setGiftId(dressUpId);
		record.setValue(0);
		record.setContent(dressUpConfig.getName() + "（"+ duration +"天）");
		record.setType(prizeType);
		activityRecordMapper.insert(record);
	}

	/**
	 * 清除缓存
	 * @param userId
	 * @param type
	 */
	private void removeCache(String userId, Integer type){
		String key = RedisConstans.USER_DRESS_UP_LIST + userId;
		String item = "";
		//删除缓存
		if(DressUpTypeEnum.PENDANT.getValue().equals(type)){//挂件
			item = String.valueOf(DressUpTypeEnum.PENDANT.getValue());
		} else if(DressUpTypeEnum.USER_LABEL.getValue().equals(type)){
			item = String.valueOf(DressUpTypeEnum.USER_LABEL.getValue());
		} else if(DressUpTypeEnum.HOME_DECORATION.getValue().equals(type)){//账号标签
			item = String.valueOf(DressUpTypeEnum.HOME_DECORATION.getValue());
		} else if(DressUpTypeEnum.HOME_DECORATION.getValue().equals(type)){//主页装饰动画
			item = String.valueOf(DressUpTypeEnum.HOME_DECORATION.getValue());
		} else if(DressUpTypeEnum.TAIL_LIGHT.getValue().equals(type)){//尾灯
			item = String.valueOf(DressUpTypeEnum.TAIL_LIGHT.getValue());
		} else if(DressUpTypeEnum.BUBBLE.getValue().equals(type)){//气泡框
			item = String.valueOf(DressUpTypeEnum.BUBBLE.getValue());
		}
		redisUtil.hdel(key,item);
		if(DressUpTypeEnum.PENDANT.getValue().equals(type)){//挂件
			item = String.valueOf(-DressUpTypeEnum.PENDANT.getValue());
			redisUtil.hdel(key,item);
		}
	}



	@Deprecated
	@Override
	public GiftConfig savePrize(Integer activityId, String userId, Integer giftId, Integer type, Integer num){
		ActivityPrize prize = new ActivityPrize();
		prize.setActivityId(activityId);
		prize.setGiftId(giftId);
		prize.setType(type);
		prize.setNum(num);
		return savePrize(new PrizeDto(userId, prize));
	}


	@Deprecated
	@Override
	public void saveFamilyLabel(Integer activityId, Integer type, String familyId, Integer dressConfigId, String remark){
		ActivityPrize prize = new ActivityPrize();
		prize.setActivityId(activityId);
		prize.setGiftId(dressConfigId);
		prize.setType(type);
		prize.setNum(1);
		saveFamilyLabel(new PrizeDto(familyId, prize, remark));
	}


	@Deprecated
	@Override
	public void savePrizeToUserDress(Integer activityId, String userId, Integer giftId, Integer prizeType, String remark){
		ActivityPrize prize = new ActivityPrize();
		prize.setActivityId(activityId);
		prize.setGiftId(giftId);
		prize.setType(prizeType);
		prize.setNum(1);
		savePrizeToUserDress(new PrizeDto(userId, prize, remark));
	}


	/**
	 * 领取并保存礼物和记录
	 * @param
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void  savePrizeToUserDress(PrizeDto prizeDto){
		String userId = prizeDto.getUserId();
		ActivityPrize prize = prizeDto.getPrize();
		Integer giftId = prize.getGiftId();
		Integer activityId = prize.getActivityId();
		Integer prizeType = prize.getType();
		String remark = prizeDto.getRemark();
		if (userId == null) {
			log.error("methodName:savePrizeToUserDress, error=用户Id不能为空");
			return;
		}
		if (giftId == null) {
			log.error("methodName:savePrizeToUserDress, error=装扮id不能为空");
			return;
		}
		// 获取奖品信息
		GiftConfig giftConfig = giftConfigMapper.selectById(giftId);
		if (giftConfig == null) {
			log.error("methodName:savePrizeToUserDress,giftId={},error=giftConfig不存在", giftId);
			return;
		}
		SysDict sysDict = sysDictMapper.selectById(giftConfig.getDressId());
		if (sysDict == null) {
			log.error("methodName:savePrizeToUserDress, error=获取装扮信息失败");
			return;
		}
		LocalDateTime now = LocalDateTime.now();
		//新增数据组装
		UserDressUp userDressUp = new UserDressUp();
		userDressUp.setUserId(userId);
		userDressUp.setType(Integer.valueOf(sysDict.getProperty1()));
		userDressUp.setDressId(sysDict.getId());
		userDressUp.setPrice(Integer.valueOf(sysDict.getProperty5()));
		userDressUp.setStatus(0);
		userDressUp.setDuration(StringUtils.isBlank(sysDict.getProperty4()) ? 0 : Integer.valueOf(sysDict.getProperty4()));
		userDressUp.setLimitedType(Integer.valueOf(sysDict.getProperty7()));
		userDressUp.setCreateTime(now);
		userDressUp.setUpdateTime(now);
		userDressUp.setLimitedType(2);
		userDressUp.setRemark(remark);
		userDressUpService.save(userDressUp);
		//删除缓存
		//removeCache(user.getUserId(), type);
		//插入领取记录表
		ActivityRecord record = new ActivityRecord();
		record.setActivityId(activityId);
		record.setUserId(userId);
		record.setGiftId(sysDict.getId());
		record.setValue(0);
		record.setContent(sysDict.getName() + "（"+ sysDict.getProperty4() +"天）");
		record.setType(prizeType);
		activityRecordMapper.insert(record);
		//返回
		//插入奖励记录表
		ActivityAward award = new ActivityAward();
		award.setActivityId(activityId);
		award.setType(prizeType);
		award.setUserId(userId);
		award.setGiftId(giftId);
		award.setSource(prize.getSource());
		award.setIcon(prize.getIcon());
		award.setNum(prize.getNum());
		award.setName(giftConfig.getName());
		award.setUseNum(prize.getUseNum());
		award.setRoundId(prize.getRoundId());
		award.setTotalValue(prize.getTotalValue());
		activityAwardMapper.insert(award);
	}

	/**
	 * 领取并保存礼物和记录
	 * @param userId
	 * @param giftId
	 * @return
	 */
	/*@Override
	@Transactional(rollbackFor = Exception.class)
	public void receiveGift(Integer activityId, String userId, Integer giftId){
		//判断是否已领取
		*//*if(isReceive(activityId, userId, giftId)){
			return;
		}*//*
		// 获取奖品信息
		GiftConfig giftConfig = giftConfigMapper.selectById(giftId);
		if (giftConfig == null) {
			log.error("methodName:receiveGift,giftId={},error=giftConfig不存在", giftId);
			return;
		}
		Activity activity = activityService.getActivity(activityId);
		// 装饰物
		if (giftConfig.getGiftType().equals(1)) {
			SysDict sysDict = sysDictMapper.selectById(giftId);
			if (sysDict == null) {
				log.error("methodName:receiveGift,giftId={},error=sysDict不存在", giftId);
				return;
			}
			// 保存装扮礼物数据
			LocalDateTime nowDateTime = LocalDateTime.now();
			UserDressUp dressUp = new UserDressUp();
			dressUp.setUserId(userId);
			dressUp.setType(Integer.valueOf(sysDict.getProperty1()));
			dressUp.setDressId(sysDict.getId());
			dressUp.setPrice(Integer.valueOf(sysDict.getProperty5()));
			dressUp.setStatus(0);
			dressUp.setDuration(StringUtils.isBlank(sysDict.getProperty4()) ? 0 : Integer.valueOf(sysDict.getProperty4()));
			dressUp.setLimitedType(Integer.valueOf(sysDict.getProperty7()));
			dressUp.setCreateTime(nowDateTime);
			dressUp.setUpdateTime(nowDateTime);
			userDressUpMapper.insert(dressUp);
		} else {
			UserGiftBackpack backpack = new UserGiftBackpack();
			backpack.setUserId(userId);
			backpack.setGiftId(giftId);
			backpack.setName(giftConfig.getName());
			backpack.setValue(giftConfig.getValue());
			backpack.setIconUrl(giftConfig.getIconUrl());
			backpack.setEffects(giftConfig.getEffects());
			backpack.setLovenum(giftConfig.getLovenum());
			backpack.setStatus(0);
			backpack.setSource(3);
			backpack.setGiftType(giftConfig.getGiftType());
			userGiftBackpackMapper.insert(backpack);
		}
		//保存赠送记录到用户账本表
		UserAccountBook accountBook = new UserAccountBook();
		accountBook.setCurrencyType(6);
		accountBook.setOrderId(String.valueOf(giftId));
		accountBook.setAccountTitle(activity.getName() + "领取");
		accountBook.setReceivingAccount(userId);
		accountBook.setReceivingAmount(0);
		accountBook.setPaymentAccountTotal(0);
		accountBook.setPaymentAccountBalance(0);
		accountBook.setPaymentAmount(0);
		accountBook.setNote(activity.getName() + "奖品");
		userAccountBookMapper.insert(accountBook);
		//插入领取记录表
		ActivityRecord record = new ActivityRecord();
		record.setActivityId(activityId);
		//record.setType(0);
		record.setUserId(userId);
		record.setGiftId(giftId);
		activityRecordMapper.insert(record);
	}*/

	//是否已领取
	private boolean isReceive(Integer activityId, String userId, Integer giftId){
		LambdaQueryWrapper<ActivityRecord> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(ActivityRecord::getActivityId, activityId).eq(ActivityRecord::getUserId, userId).eq(ActivityRecord::getGiftId, giftId);
		wrapper.last("limit 1");
		ActivityRecord record = activityRecordMapper.selectOne(wrapper);
		if(record != null){
			return true;
		}
		return false;
	}


}
